package com.movie.api.mapper;

import com.movie.api.model.entity.Film;
import com.movie.api.model.vo.FilmInfoAndStarVO;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.mapstruct.Mapper;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Mapper
public interface FilmTimeMapper {
    List<Film> getByAll();

    List<Film> getByWeek();

    List<Film> getByMonth();

    void viewAt(Integer movie_id);

    @Select("SELECT * FROM film WHERE name LIKE CONCAT('%', #{searchText}, '%')")
    List<Film> selectByName(String searchText);

    @Select("SELECT * FROM film WHERE director LIKE CONCAT('%', #{searchText}, '%')")
    List<Film> selectByDirector(String searchText);

    List<Film> selectByActors(String searchText);

    List<Film> getPageByAll(Integer startIndex, Integer pageSize);

    @Select("SELECT COUNT(*) FROM film;")
    Integer count();

    List<Film> getPageByMonth(int startIndex, Integer pageSize);

    List<Film> getPageByWeek(int startIndex, Integer pageSize);

    @Update("UPDATE film SET hot = hot + 1 WHERE id = #{filmId};")
    void addhot(Integer filmId);

    @Select("SELECT f.type, COUNT(v.id) AS view_count " +
            "FROM film_views v " +
            "JOIN film f ON v.movie_id = f.id " +
            "GROUP BY f.type")
    List<Map<String, Object>> countViewsByType();

    @Select("SELECT DATE_FORMAT(viewed_at, '%m-%d') AS view_date, COUNT(*) AS view_count " +
            "FROM film_views " +
            "WHERE viewed_at >= CURDATE() - INTERVAL 6 DAY AND viewed_at < CURDATE() + INTERVAL 1 DAY " +
            "GROUP BY view_date " +
            "ORDER BY view_date")
    List<Map<String, Object>> countViewsLastSevenDays();

    @Select("SELECT fv.*, COUNT(*) AS views " +
            "FROM film_views v " +
            "LEFT JOIN film fv ON fv.id = v.movie_id " +
            "WHERE v.viewed_at >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH)" +
            "GROUP BY v.movie_id " +
            "ORDER BY views DESC")
    List<Map<String, Object>> getMovieViewsWithinLast30Days();

    @Select("SELECT fv.*, COUNT(*) AS views " +
            "FROM film_views v " +
            "LEFT JOIN film fv ON fv.id = v.movie_id " +
            "GROUP BY v.movie_id " +
            "ORDER BY views DESC")
    List<Map<String, Object>> getMovieViewsWithinAllDays();

    List<FilmInfoAndStarVO> getFilmByComment(Integer startIndex, Integer pageSize);
}
